import { Notify, Dialog } from "quasar";
import { computed, provide, ref } from "vue";
import { v4 as uuidv4 } from "uuid";
import { useAPIStore } from "stores/api/index.js";
import { api } from "boot/axios.js";
import { useFunctionsStore } from "stores/functions/index.js";

const connected = ref(false);
export const deviceMap = ref({});
export const devices = computed(() => Object.values(deviceMap.value));

let ws = null;
export default function centerWs() {
  const clientID = ref(uuidv4());
  provide("clientID", clientID);

  api.get(useAPIStore().centerUrl + "center/status").then((rs) => {
    rs.data.forEach((item) => {
      deviceMap.value[item.device] = item;
    });
  });

  /**
   * 创建WebSocket连接
   */
  const createWs = () => {
    ws = new WebSocket(
      "ws://" + useAPIStore().centerIP + ":8741/frontend/" + clientID.value
    );
    initWs();
  };

  let rec;
  /**
   * 重连函数
   */
  const reConnect = () => {
    console.log("中控Ws 尝试重连");
    if (connected.value) return;
    rec && clearTimeout(rec);
    rec = setTimeout(createWs, 5000);
  };

  /**
   * 设置心跳
   */
  const heartCheck = {
    timeoutObj: null,
    start: () => {
      heartCheck.timeoutObj = setTimeout(function () {
        if (connected.value) {
          ws.send("heartbeat");
        } else {
          reConnect();
        }
      }, 10000);
    },
    reset: () => {
      clearTimeout(heartCheck.timeoutObj);
      heartCheck.start();
    },
  };

  /**
   * 初始化WebSocket
   */
  const initWs = () => {
    ws.onclose = () => {
      connected.value = false;
      clearTimeout(heartCheck.timeoutObj);
    };

    ws.onerror = () => {
      connected.value = false;
      reConnect();
    };

    ws.onopen = () => {
      connected.value = true;
      heartCheck.start();
      Notify.create({
        type: "positive",
        message: "已连接中控Websocket",
        position: "top",
      });
    };

    ws.onmessage = (e) => {
      heartCheck.reset();
      // 接收服务器返回的数据
      if (e.data !== "heartbeat") {
        const rsData = JSON.parse(e.data);
        switch (rsData.type.valueOf()) {
          case "notify":
            Notify.create({
              message: rsData.content.message,
              type: rsData.content.type,
            });
            break;
          case "log":
            if (useFunctionsStore().logWindow) {
              if (
                rsData.content.source === "ros" ||
                rsData.content.source === "amr"
              ) {
                warning(
                  "设备" +
                    rsData.content.device +
                    "：" +
                    rsData.content.description
                );
              } else {
                Notify.create({
                  type: "info",
                  message:
                    rsData.content.device + "上报：" + rsData.content.type,
                });
              }
            } else {
              Notify.create({
                type: "info",
                message:
                  "设备" +
                  rsData.content.device +
                  "上报：" +
                  rsData.content.type,
              });
            }
            break;
          case "status":
            deviceMap.value[rsData.content.device] = rsData.content;
            break;
          case "remove":
            delete deviceMap.value[rsData.content];
            break;
        }
      }
    };
  };

  function warning(message) {
    Dialog.create({
      class: "text-bold text-h5 text-negative",
      message,
      position: "top",
      persistent: true,
      ok: {
        label: "确认",
        class: "text-bold text-h6 full-width",
        flat: true,
        style: "min-width:10rem",
      },
    });
  }

  createWs();
}
/**
 * 断开ws
 */
export function closeCenterWs() {
  ws.close();
}
